package com.example.springboot01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot01.config.TeacherContextHolder;
import com.example.springboot01.entity.Course;
import com.example.springboot01.entity.Student;
import com.example.springboot01.entity.Teacher;
import com.example.springboot01.entity.User;
import com.example.springboot01.mapper.TeacherMapper;
import com.example.springboot01.req.PageQueryReq;
import com.example.springboot01.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Resource
    private UserService userService;

    @Resource
    private  StudentService service;

    @Resource
    private TeacherClassService tcs;

    @Resource
    private CourseService courseService;

    @Override
    public IPage<Teacher> getPage(PageQueryReq req) {
        return this.page(new Page<Teacher>(req.getCurrent(), req.getSize()));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addTeacher(Teacher s) {
        User u = new User();
        u.setUsername(s.getTeacherNo());
        u.setPassword("qwer123654875rewq");
        u.setUserType(1);
        userService.save(u);
        s.setUserId(u.getId());
        this.save(s);
    }

    @Override
    public Teacher getByUserId(Serializable userId) {
        return this.getOne(new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getUserId, userId)
        );
    }

    @Override
    public List<Student> listStudent() {
        final Integer id = TeacherContextHolder.get();
        List<Integer> classIds = tcs.queryClassIdByTeacher(id);
        return service.queryByClasses(classIds);
    }

    @Override
    public Course getCourse() {
        final Integer id = TeacherContextHolder.get();
        return courseService.getByTeacher(id);
    }
}
